<?php
namespace Controller;

class Controller extends \Ypf\Core\Controller{

    const METHOD_TYPE_GET    =   2; //GET方法
    const METHOD_TYPE_POST   =   8; //POST方法
	protected $configall;
    public $module_name;
    public $controller_name;
    public $function_name;
    public $post;
    public $get;
    public $req;
	 public function __construct(){
         parent::__construct();
         $this->configall = \Ypf\Lib\Config::$config;//config

         !defined('REQUEST_METHOD') && define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
         !defined('IS_GET') && define('IS_GET',        REQUEST_METHOD =='GET' ? true : false);
         !defined('IS_POST') && define('IS_POST',       REQUEST_METHOD =='POST' ? true : false);
         !defined('IS_PUT') && define('IS_PUT',        REQUEST_METHOD =='PUT' ? true : false);
         !defined('IS_DELETE') && define('IS_DELETE',     REQUEST_METHOD =='DELETE' ? true : false);

         $this->post = $this->request->post;
         $this->get = $this->request->get;
         $this->req = array_merge($this->get, $this->post);
     }


    //是否已登录
    public function _isLogin(){
        return isset($_SESSION[$this->configall['common']['USER_AUTH_KEY']]) && isset($_SESSION[$this->configall['common']['USER_AUTH_KEY']]['id']) ;
    }
	 /**
     * 是否AJAX请求
     * @access protected
     * @return bool
     */
    protected function isAjax() {
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
            if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
                return true;
        }
        return false;
    }
	
	/**
	 * is pjax request
	 */
	 protected function isPjax(){
		return (array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX']) || (array_key_exists('X_PJAX', $_SERVER) && $_SERVER['X_PJAX']);
	 }
	 
	/**
	 * 有不存在的请求时调用
	 * isPost() ...
	 */
	public function __call($method,$args=null){
		switch(strtolower($method)){
			case 'ispost'   :
            case 'isget'    :
            case 'ishead'   :
            case 'isdelete' :
            case 'isput'    :
			return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2));
			default:
			die("controller {$this->getRoute()} function ( $method ) not exist...");
		}
	}
	
	/*
	 * redirect
	 */
	 protected  function  redirect($url, $delay=0, $msg='' ,$params=array()){
		 redirect($url,$delay,$msg);
	 }
	
	/**
	 * get route
	 */
	 protected function getRoute(){
		return isset($this->request->get['route'])?$this->request->get['route']:'';
	 }
	 
	 /**
	  *
	  */
	 protected function getAction(){
		$route = $this->getRoute(); //\Controller\Home\Account\Index\index
		if($route){
			$className = get_class($this); //Controller\Home\Account\Index
			$pos = strripos($route, '\\');
			return substr($route, $pos+1);
		}
	 }

    /**
     * 获取当前操作的模块、控制器、方法名
     * @return array
     */
    protected function getActions(){
        $res = array();
        $route = $this->getRoute(); //\Controller\Home\Account\Index\index
        if($route){
            $actions = explode('\\', $route);
            $this->function_name = array_pop($actions);
            $this->controller_name = array_pop($actions);
            $this->module_name = array_pop($actions);
            !defined('MODULE_NAME') && define('MODULE_NAME', $this->module_name);
            !defined('CONTROLLER_NAME') && define('CONTROLLER_NAME', $this->controller_name);
            !defined('ACTION_NAME') && define('ACTION_NAME', $this->function_name);
            !defined('FUNCTION_NAME') && define('FUNCTION_NAME', $this->function_name);

        }
        return $res;
    }
	 
	protected function dispatchJump($message, $status=1, $jumpUrl='', $waitSecond = 0, $ajax=false, $closeWin=false){
		if($ajax){
			$data['info']   =   $message;
            $data['status'] =   $status;
            $data['url']    =   $jumpUrl;
            $this->ajax->output($data);
		}
		$this->view->assign('msgTitle', $status?$this->configall['common']['DISPATH_JUMP']['OPERATION_SUCCESS']:$this->configall['common']['DISPATH_JUMP']['OPERATION_FAIL']);
		$this->view->assign('closeWin', $closeWin);
		$this->view->setTemplateDir(__VIEW_COMMON__); //set template dir
		switch($status){
			case 1:
				$this->view->assign('message', $message);
				$this->view->assign('waitSecond', $waitSecond?$waitSecond:$this->configall['common']['DISPATH_JUMP']['SUCCESS_WAIT_SECOND']);
				$this->view->assign("jumpUrl", $closeWin?$this->configall['common']['DISPATH_JUMP']['CLOSE_WIN_JUMP_URL']:($jumpUrl?$jumpUrl:$this->configall['common']['DISPATH_JUMP']['SUCCESS_JUMP_URL']));
				$this->view->display($this->configall['common']['DISPATH_JUMP']['TPL_JUMP']);
				break;
			case 0:
				$this->view->assign('error', $message);
				$this->view->assign('waitSecond', $waitSecond?$waitSecond:$this->configall['common']['DISPATH_JUMP']['ERROR_WAIT_SECOND']);
				$this->view->assign("jumpUrl", $closeWin?$this->configall['common']['DISPATH_JUMP']['CLOSE_WIN_JUMP_URL']:($jumpUrl?$jumpUrl:$this->configall['common']['DISPATH_JUMP']['ERROR_JUMP_URL']));
				$this->view->display($this->configall['common']['DISPATH_JUMP']['TPL_JUMP']);
				exit;
				break;
		}
	 }
		
	 protected function error($message, $jumpUrl='', $waitSecond = 0, $ajax=false, $closeWin=false) {
		$this->dispatchJump($message, 0, $jumpUrl, $waitSecond, $ajax, $closeWin);
     }
	 
	 protected function success($message, $jumpUrl='', $waitSecond = 0, $ajax=false, $closeWin=false) {
		$this->dispatchJump($message, 1, $jumpUrl, $waitSecond, $ajax, $closeWin);
     }

    /**
     * Ajax方式返回数据到客户端
     * @author xuanskyer | <furthestworld@icloud.com>
     * @time    2015-6-1 09:44:38
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @param int $json_option 传递给json_encode的option参数
     * @return void
     */
    protected function ajaxReturn($data,$type='JSON',$json_option=0) {
        if(empty($type)) $type  =   C('DEFAULT_AJAX_RETURN');
        switch (strtoupper($type)){
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data,$json_option));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler  =   isset($this->configall['common']['DEFAULT_JSONP_HANDLER']) ? $this->configall['common']['DEFAULT_JSONP_HANDLER'] : 'callback';
                exit($handler.'('.json_encode($data,$json_option).');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
            default     :
                exit(json_encode($data,$json_option));
        }
    }

    //获取登陆用户id
    public function getMemberId(){
        return isset($_SESSION[$this->configall['common']['USER_AUTH_KEY']]['id'])?$_SESSION[$this->configall['common']['USER_AUTH_KEY']]['id']:null;
    }
    //获取登陆用户信息
    public function getMemberInfo(){
        return isset($_SESSION[$this->configall['common']['USER_AUTH_KEY']])?$_SESSION[$this->configall['common']['USER_AUTH_KEY']]:null;
    }

    /**
     * 记录操作日志
     * @param array $params
     * @return bool
     */
    public function saveLog($params = array()){
        $this->getActions();
        $user_info = $this->getMemberInfo();
        $nickname = isset($user_info['nickname']) ? $user_info['nickname'] : '';
        $init_params['user_id'] = isset($params['user_id']) ? $params['user_id'] : $this->getMemberId();
        $init_params['nickname'] = isset($params['nickname']) ? $params['nickname'] : $nickname;
        $init_params['module'] = isset($params['module']) ? $params['module'] : $this->module_name;
        $init_params['controller'] = isset($params['controller']) ? $params['controller'] : $this->controller_name;
        $init_params['action'] = isset($params['action']) ? $params['action'] : $this->function_name;
        $init_params['method'] = isset($params['method']) ? $params['method'] : self::METHOD_TYPE_POST;

        !isset($params['message']) && $params['message'] = '';
        !isset($params['keyword']) && $params['keyword'] = '';
        !isset($params['obj_user']) && $params['obj_user'] = '';
        !isset($params['domain']) && $params['domain'] = '';
        !isset($params['remark']) && $params['remark'] = '';
        $init_params['params'] = json_encode($params);

        $userLogService = new \Service\Log\LogService($init_params);
        $res = $userLogService->save( $params['message'], $params['keyword'], $params['obj_user'], $params['domain'], $params['remark']);
        return $res;
    }

    /**
     * 请求合法验证过滤器
     */
    public function operate(){
        $operate = $this->req['op'];
        if(method_exists($this, $operate)){
            $this->$operate();
        }else{
            echo "调用方法({$operate})不存在\r\n";
        }
    }
}